import jwt from 'jsonwebtoken';
import { Request, Response, NextFunction } from 'express';
import response from '../utils/response';

const JWT_SECRET = process.env.JWT_SECRET || 'your-secret-key-change-in-production';

interface User {
  id: number;
  username: string;
  role: string;
}

// 生成 JWT Token
const generateToken = (user: User) => {
  return jwt.sign(
    { 
      id: user.id, 
      username: user.username,
      role: user.role 
    },
    JWT_SECRET,
    { expiresIn: '7d' }
  );
};

// 验证 JWT Token 中间件
const authenticateToken = (req: Request, res: Response, next: NextFunction): void => {
  const authHeader = req.headers['authorization'];
  const token = authHeader && authHeader.split(' ')[1];

  if (!token) {
    response.error(res, '未提供认证令牌', 401);
    return;
  }

  jwt.verify(token, JWT_SECRET, (err: any, user: any) => {
    if (err) {
      response.error(res, '认证令牌无效或已过期', 403);
      return;
    }
    (req as any).user = user;
    next();
  });
};

// 验证管理员权限
const requireAdmin = (req: Request, res: Response, next: NextFunction): void => {
  const userReq = req as any;
  if (!userReq.user || userReq.user.role !== 'admin') {
    response.error(res, '需要管理员权限', 403);
    return;
  }
  next();
};

export {
  generateToken,
  authenticateToken,
  requireAdmin
};